package com.xxl.job.admin.controller;

import com.xxl.job.admin.dto.JobResultDTO;
import com.xxl.job.admin.service.CronJobService;
import com.xxl.job.admin.service.InitCrontabService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wenhonghao
 * @email 18167784149@163.com
 * @description: 用来接收浏览器回调结果的控制器
 * 可根据回调结果判断执行器是否成功执行
 */
@RestController
@RequestMapping("/job-result")
public class JobResultController {
    private final Map<String, JobResultDTO> executionResults = new ConcurrentHashMap<>();

    @Autowired
    private InitCrontabService initCrontabService;


    @PostMapping(value = "/receive", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> receiveJobResult(@RequestBody JobResultDTO jobResultDTO) {
        System.out.println("调度中心已收到回调结果" + jobResultDTO);
        Map<String, Object> response = new HashMap<>();
        try {
            // 根据 IP 地址作为 key，保存执行结果
            String serverIp = jobResultDTO.getServerIp();
            clearExecutionResult(serverIp);
            executionResults.put(serverIp, jobResultDTO);

            response.put("success", true);
            response.put("message", "回调结果接收成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "回调结果处理失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PostMapping(value = "/init", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> initCrontab(@RequestBody JobResultDTO jobResultDTO) {
        System.out.println("调度中心已收到回调结果" + jobResultDTO);
        Map<String, Object> response = new HashMap<>();
        clearExecutionResult(jobResultDTO.getServerIp());
        try {
            // 初始化或更新数据库中的定时任务
            if (jobResultDTO.getCronTasks() != null && !jobResultDTO.getCronTasks().isEmpty()) {
                String serverUser = jobResultDTO.getUser();  // 从执行器返回的数据中获取用户信息
                initCrontabService.initializeCronJobs(jobResultDTO.getCronTasks(),jobResultDTO.getServerIp(), serverUser);
            }
            response.put("success", true);
            response.put("message", "回调结果接收成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "回调结果处理失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 获取最近的执行结果
    public JobResultDTO getLastExecutionResult(String serverIp) {
        return executionResults.get(serverIp);
    }

    // 清除执行结果（每次调用前清除上次记录）
    public void clearExecutionResult(String serverIp) {
        executionResults.remove(serverIp);
    }
}
